<template>
  <div>
    <div class="front">
      <div class="front-left">
        <!-- <el-radio-group class="front-select" v-model="outboundForm.orderType" @change="changeOutboundType">
          <el-radio-button label="1" size="large">客户借货</el-radio-button>
          <el-radio-button label="2" size="large">市场还货</el-radio-button>
          <el-radio-button label="0" size="large">销售出库</el-radio-button>
        </el-radio-group> -->
        <el-radio-group v-model="radioValue" style="margin-bottom: 20px;">
          <el-radio-button label="1">客户借货</el-radio-button>
          <el-radio-button label="2">市场还货</el-radio-button>
          <el-radio-button label="0">销售出库</el-radio-button>
        </el-radio-group>
        <el-form class="front-form" :model="outboundForm" ref='outboundRef' :rules="outboundOrderRules"
          label-width="120px">
          <el-form-item class="front-input" v-if="outboundForm.outboundShow1" label="出借客户" :required="true"
            prop="clientId">
            <el-select v-model="outboundForm.clientId" placeholder="请选择" style="width: 150px;">
              <el-option v-for="item in clientList" :key="item.id" :label="item.clientName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item class="front-input" v-if="outboundForm.outboundShow1" label="出借天数" :required="true"
            prop="lendDays">
            <el-input v-model="outboundForm.lendDays" @input="handleInputNums" style="width: 150px;"
              placeholder="请输入0-365的天数" />
          </el-form-item>
          <el-form-item class="front-input" v-if="outboundForm.outboundShow2" label="还货商户" prop="clientId"
            :required="true">
            <el-select v-model="outboundForm.clientId" placeholder="请选择" style="width: 150px;">
              <el-option v-for="item in clientList" :key="item.id" :label="item.clientName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item class="front-input" v-if="outboundForm.outboundShow2" label="入库编码" prop="inboundOrderCode"
            :required="true">
            <el-input v-model="outboundForm.inboundOrderCode" style="width: 150px;" />
          </el-form-item>
          <el-form-item class="front-input" v-if="outboundForm.outboundShow3" label="售出客户" prop="clientId"
            :required="true">
            <el-select v-model="outboundForm.clientId" placeholder="请选择" style="width: 150px;">
              <el-option v-for="item in clientList" :key="item.id" :label="item.clientName" :value="item.id" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item class="front-input" v-if="outboundForm.outboundShow3" label="结算周期" :required="true">
            <el-input v-model="outboundForm.settlementCycle" style="width: 150px;">
              <template #prepend>售后</template>
              <template #append>天</template>
            </el-input>
          </el-form-item> -->
          <el-form-item class="front-input" v-if="outboundForm.outboundShow3" label="销售价计算方式">
            <el-select v-model="outboundForm.settlementType" placeholder="请选择" style="width: 150px;">
              <el-option label="成本价百分比" value="2" />
              <el-option label="标签价百分比" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item class="front-input" v-if="outboundForm.outboundShow3" label="销售结算比率" :required="true"
            prop="settlementRatio">
            <el-input v-model="outboundForm.settlementRatio" style="width: 150px;">
              <template #append>%</template>
            </el-input>
          </el-form-item>
          <el-form-item class="front-input" label="出库备注">
            <el-input v-model="outboundForm.remark" style="width: 250px;" :rows="2" type="textarea" />
          </el-form-item>
        </el-form>
      </div>
      <div class="front-right">
        <div style="margin: 0 0 10px 0 ;">
          <el-radio-group v-model="labelType" size="small">
            <el-radio-button label="barcode">条形码上传</el-radio-button>
            <el-radio-button label="phone">拍照上传</el-radio-button>
          </el-radio-group>
        </div>
        <div v-if="labelType == 'phone'">
          <div class="right-photo">
            <video ref="videoElement" class="rigth-video" autoplay></video>
            <!-- <el-img description="No image" :src="imageUrlList" v-if="!isvideo" /> -->
            <canvas ref="canvasElement" class="right-img"></canvas>
          </div>
          <div class="right-action">
            <el-upload action="http://8.134.106.197:9001/common/uploadImage" class="upload"
              :headers="{ Authorization: token }" :show-file-list="false" accept=".png,.jpg,.jpeg,.webp"
              style="display: inline-block;" :on-preview="handlePictureCardPreview" :on-error="console.log(error)"
              :on-success="handleUpload">
              <el-button style="color:#1890ff;">上传</el-button>
            </el-upload>
            <el-button @click="takePhoto" style="color:#1890ff;margin-left: 10px;">拍照</el-button>
            <el-button @click="triggerCamera" style="color:#1890ff;">{{ cameraActive ? '关闭摄像头' : '打开摄像头' }}</el-button>
          </div>
        </div>
        <div v-if="labelType == 'barcode'" style="min-height: 220px;">
          <div class="right-input" style="display: flex;">
            <el-form style="display: flex;">
              <el-form-item label="扫描/输入条码" style="width:70%;margin-left:20px">
                <el-input v-model="outboundForm.jadeCode" @keyup.enter.native="onSearch">
                </el-input>
              </el-form-item>
              <el-button type="primary" @click="onSearch" style="margin-left: 10px;">确认</el-button>
            </el-form>
          </div>
        </div>
      </div>
    </div>

    <div class="tail">
      <div class="tail-action">
        <el-button type="primary" @click="onSubmit">操作出库</el-button>
        <el-popover placement="bottom" trigger="click">
          <template #reference>
            <el-button><el-icon>
                <List />
              </el-icon>显示设置</el-button>
          </template>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="selectedFilters" @change="handleCheckChange">
            <el-checkbox v-for="item in tableFilter.map(i => i.label)" :label="item" :key="item" />
          </el-checkbox-group>
        </el-popover>
      </div>
      <el-table :data="tableData()" border style="width: 100%" max-height="320">
        <template v-slot:empty>
          <div class="no-data">暂无数据</div>
        </template>
        <el-table-column label="货品图片" width="90">
          <template #default="scope">
            <el-image :src="'http://8.134.106.197:9001/profile' + scope.row.imageUrl" fit="contain"
              style="max-height: 50px;max-width: 30px;" :preview-teleported="true" :lazy="true"
              :preview-src-list="imgPreview" @click="previewSrcList(scope.row.imageUrl)"></el-image>
          </template>
        </el-table-column>
        <el-table-column v-for="item in outboundJadeDataColumn" :prop="item.prop" :min-width="item.minWidth"
          :width="item.width" :max-width="item.maxWidth" :label="item.label" />
        <el-table-column label="操作" width="60" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleDeleteImg(scope.row.imageId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
          layout="prev, pager, next ,total,sizes" :total="data.total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>

    <div class="optionView">
      <el-dialog v-model="dialogVisibleResult" title="检测结果" @close="handleCloseResult()" style="width: 350px;">
        <el-table :data="imageUrlList" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="40" />
          <el-table-column label="出库对象" prop="url" width="120">
            <template #default="scope">
              <el-image :src="'http://8.134.106.197:9001/profile' + scope.row.imageUrl" alt="Photo" fit="contain"
                style="max-height: 120px;max-width: 70px;" :preview-teleported="true" :lazy="true"
                :preview-src-list="imgPreview" @click="previewSrcList(scope.row.imageUrl)"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="库存对比" prop="matchUrl">
            <template #default="scope">
              <!-- <el-tooltip content="查无此货">
              </el-tooltip> -->
              <el-image :src="'http://8.134.106.197:9001/profile' + scope.row.matchUrl" alt="Photo" fit="contain"
                style="max-height: 120px;max-width: 70px;" :preview-teleported="true" :lazy="true"
                :preview-src-list="imgPreview" @click="previewSrcList(scope.row.matchUrl)">
                <template v-slot:error>
                  <i class="image-miss">{{ match_controll }}</i>
                </template>
              </el-image>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" style="margin-top: 15px;" @click="ensureJade">确认</el-button>
        <div>请<span style="font-weight: 600; color: red;">勾选</span>需要出库的对象然后选择确认</div>
      </el-dialog>
      <!-- 弹框展示列表 -->
      <el-dialog v-model="dialogVisibleList" title="货品列表" @open="initdialogVisibleList(outboundForm.jadeCode)"
        width="60%">
        <el-table :data="jadeListData" border style="width: 100%" max-height="320"
          @selection-change="handleSelectListChange">
          <template v-slot:empty>
            <div class="no-data">暂无数据</div>
          </template>
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column prop="imageUrl" label="图片">
            <template v-slot:default="scope">
              <img :src="'http://8.134.106.197:9001/profile' + scope.row.imageUrl" alt="图片"
                style="max-width: 100%; max-height: 100px;" />
            </template>
          </el-table-column>
          <el-table-column label="编号" prop="id" />
          <el-table-column label="货品名称" prop="jadeName" />
          <el-table-column label="货品类型" prop="jadeTypeName" />
          <el-table-column label="状态" prop="status">
            <template v-slot:default="scope">
              <el-tag v-if="scope.row['status'] == 1">在仓</el-tag>
              <el-tag v-if="scope.row['status'] == 2" type="danger">已借出</el-tag>
              <el-tag v-if="scope.row['status'] == 3" type="warning">已售出</el-tag>
              <el-tag v-if="scope.row['status'] == 4" type="info">还出</el-tag>
              <el-tag v-if="scope.row['status'] == 5" type="success">加工出库</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="仓库名" prop="warehouseName" />
          <el-table-column label="仓位名" prop="storageName" />
        </el-table>
        <div class="pagination">
          <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
            layout="prev, pager, next ,total,sizes" :total="data.total" @current-change="handleCurrentChange"
            @size-change="handleSizeChange" />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleList = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </span>

      </el-dialog>
    </div>
    <!-- <ListDialog ref="ListDialogRef" @submit="handleSubmit"></ListDialog> -->
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, ref, onBeforeMount, onMounted, nextTick, watch, watchEffect, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getToken } from '@/utils/auth'
import { Plus, List } from '@element-plus/icons-vue';
import { getJadeCrop, jadeMatch, getJadeFeature, getJadeInfo, getUserList, outbound, getOutboundOrderCode, altJadeStatus, getJadeByCodeOrImg } from '@/api/outbound/outbound'
import ShowListDialog from '@/views/outbound/ShowListDialog.vue';
import ListDialog from '@/components/ListDialog.vue'
import axios from 'axios'

export default defineComponent({
  name: "HomeView",
  components: {
    Plus, List, ShowListDialog, ListDialog
  },
  setup() {
    const outboundRef = ref(null)
    const videoElement = ref(null);//拍照相关参数
    const canvasElement = ref(null);
    const cameraActive = ref(false)
    const videoStream = ref(null)
    const dialogVisibleDetails = ref(false)
    const checkAll = ref(true)//显示设置全选参数
    const isIndeterminate = ref(false)
    const dialogVisibleImg = ref(false)
    const dialogVisibleResult = ref(false)
    const match_controll = ref('识别中')


    const token = ref('')
    const clientList = ref([])//客户列表
    const imageUrlList = ref([])//图片相关参数

    const dialogImageUrl = ref('')

    const imgPreview = ref([])
    const tempData = ref([])
    const outboundJadeInfoData = ref([])

    const outboundOrderRules = reactive({//表单验证
      clientId: [{ required: true, message: '出库客户不能为空', trigger: 'change' },],
      inboundOrderCode: [{ required: true, message: '借货入库单的入库编码不得为空', trigger: 'change' }],
      lendDays: [{ required: true, message: '出借天数不能为空', trigger: 'change' },],
      settlementCycle: [{ required: true, message: '结算百分比不能为空', trigger: 'change' },
      { validator: checkPercent, trigger: 'change' }]
    });
    const outboundForm = reactive({
      lendDays: '',
      clientId: '',
      validDate: '',
      orderType: 2,
      jades: [],
      remark: '',
      settlementType: '标签价百分比',
      settlementRatio: '',
      inboundOrderCode: '',
      outboundShow1: false,
      outboundShow2: false,
      outboundShow3: false,
      deptId: '1',
    });
    const outboundJadeDataColumn = ref([])
    const selectedFilters = ref([])
    const tableFilter = ref([
      { label: '货品编码', prop: 'jadeCode', width: '200', isSelected: true },
      { label: '入库单单号', prop: 'orderCode', width: '200', isSelected: true },
      { label: '品类', prop: 'jadeTypeName', width: '60', isSelected: true },
      { label: '成本价', prop: 'jadeCost', width: '70', isSelected: true },
      { label: '标签价', prop: 'jadeTagPrice', Width: '70', isSelected: true },
      { label: '供应商', prop: 'supplierName', width: '70', isSelected: true },
      // { label: '货品状态', prop: 'inventoryStatus', width: '90', isSelected: true },
      { label: '入库仓库', prop: 'warehouseName', width: '120', isSelected: true },
      { label: '入库仓位', prop: 'storageName', width: '120', isSelected: true },
      { label: '入库类型', prop: 'orderType', width: '120', isSelected: true },
      { label: '入库人员', prop: 'createBy', width: '120', isSelected: true },
      { label: '入库时间', prop: 'createTime', minWidth: '100', isSelected: true },
      { label: '备注', prop: 'remark', minWidth: '80', maxWidth: '80', isSelected: true },
      // { label: '数量', prop: 'jadeQuantity', width: '60', isSelected: true },
    ])

    // 是拍照还货或者条形码还货
    const labelType = ref('barcode')

    // 是否展示列表弹窗
    const dialogVisibleList = ref(false)


    // 货品列表数据
    const jadeListData = ref([])

    // 获取列表数据
    const initdialogVisibleList = (jadeCode) => {
      getJadeByCodeOrImg({ barcode: jadeCode, status: 1 }).then((res) => {
        if (res.code == 500) {
          ElMessage.warning(res.msg)
        } else {
          jadeListData.value = res.data
        }
        // console.log('jadeListData', jadeListData);
        // outboundJadeInfoData.value.push(res.rows)
      })
    }

    // 多选数据
    const multipleSelectList = ref([])

    // 处理多选
    const handleSelectListChange = (val) => {
      multipleSelectList.value = val
    }

    // 多选框确定
    const handleConfirm = () => {
      // 将multipleSelectList的数据添加到数据表中
      multipleSelectList.value.forEach((item) => {
        let tag = true
        const id = item.id
        outboundJadeInfoData.value.forEach(item => {
          if (id == item.id) {
            tag = false
          }
        })
        if (tag) {
          outboundJadeInfoData.value.push(item)
        }
      })
      dialogVisibleList.value = false
    }

    let ListDialogRef = ref(null)

    const handleSubmit = (data) => {
      console.log(data)
    }

    onBeforeMount(() => {//获取数据
      token.value = getToken()
      getUserList().then((res) => {
        clientList.value = res.rows
      })
      getOutboundOrderCode().then((res) => {
        outboundForm.orderCode = res
      })
    })

    onMounted(() => {
      outboundForm.outboundShow2 = true
      tableFilter.value.forEach(function (item, index) {
        if (item.isSelected) {
          selectedFilters.value.push(item.label)
          outboundJadeDataColumn.value.push(item)
        }
      })
    })

    const handlePictureCardPreview = (uploadFile) => {  //图片预览
      dialogImageUrl.value = uploadFile.url
      dialogVisibleImg.value = true
    }
    //表格用到的参数
    const state = reactive({
      data: {
        page: 1,
        limit: 10,
        total: outboundJadeInfoData.value.length,
      },
    });
    // 前端限制分页（tableData为当前展示页表格）
    const tableData = () => {
      return outboundJadeInfoData.value
    };
    //改变页码
    const handleCurrentChange = (e) => {
      state.page = e;
    };
    //改变页数限制
    const handleSizeChange = (e) => {
      state.limit = e;
    };

    function checkPercent(rule, value, callback) {
      if (value >= 0 && value <= 100) {
        callback();
      } else {
        callback(new Error('请输入0到100之间的数字'));
      }
    };

    const takePhoto = () => { //调用摄像头后拍照
      const video = videoElement.value
      const canvas = canvasElement.value
      if (cameraActive.value) {
        if (video) try {
          // 将视频画面绘制到画布上
          const context = canvas.getContext('2d');
          // canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
          const devicePixelRatio = window.devicePixelRatio || 1;

          // 设置 Canvas 元素的实际大小
          canvas.width = 1200 * devicePixelRatio;   // 宽度为 400 像素
          canvas.height = 900 * devicePixelRatio;  // 高度为 300 像素

          // 缩放 Canvas 以适应屏幕
          context.scale(devicePixelRatio, devicePixelRatio);

          // 绘制一些内容
          context.fillStyle = 'red';
          context.drawImage(video, 0, 0, canvas.width, canvas.height);
          // 将画布内容转换为图片 URL
          // 将canvas内容转换为Blob对象
          canvas.toBlob(blob => {
            // 使用Blob对象创建URL
            const formData = new FormData()
            formData.append("file", blob, "image.png")
            // 使用 Axios 发送 POST 请求
            axios.post("http://8.134.106.197:9001/common/uploadImage", formData, {
              headers: {
                "Content-Type": "multipart/form-data",
                "Authorization": token.value,
              },
            }).then((res) => {
              getJadeCrop({ image_path: res.data.url.slice(34) }).then((res_crop) => {//分割图片
                if (res_crop.code == 500) {//是否分割出图片
                  ElMessage.error(res_crop)
                } else {
                  for (var key in res_crop.result) {
                    imageUrlList.value.push({ imageId: key, imageUrl: res_crop.result[key] })
                  }
                  let imageIds = imageUrlList.value.map(item => item.imageId)
                  getJadeFeature({ data: imageUrlList.value }).then(res => {
                    jadeMatch(imageIds).then((res_match) => {//匹配翡翠
                      if (res_match.match_result == '') {
                        ElMessage.error('无法识别该货品')
                        imageUrlList.value = []
                      } else {
                        // console.log(res_match.match_result)
                        imageUrlList.value = imageUrlList.value.map(item => {//放入匹配结果
                          const imageId = item.imageId;
                          const bestMatch = Array.isArray(res_match.match_result) ? res_match.match_result[imageId] : '';
                          // console.log('匹配的图片' + bestMatch)
                          return { ...item, best_match: bestMatch };
                        })
                        getJadeInfo({ imageIds: imageUrlList.value.map(i => i.best_match) }).then((jadeInfos) => {//获取翡翠信息
                          jadeInfos.data.forEach(jade => {
                            imageUrlList.value.forEach(img => {
                              if (jade.imageId == img.best_match) {
                                img.matchUrl = jade.imageUrl
                                img.details = jade
                              }
                            })
                          })
                          console.log(imageUrlList.value)
                        })
                      }
                    })
                  })
                  dialogVisibleResult.value = true  //打开确认列表
                }
              })
            }).catch((error) => {
              // 处理上传失败的错误
              console.error(error)
            })
          });
        }
          catch (error) {
            console.log(error)
            ElMessage.error('摄像头拍照失败')
          }
      }
      else {
        ElMessage.error('请先打开摄像头')
      }
    };

    const triggerCamera = async () => { //启动摄像头
      if (cameraActive.value) {
        videoStream.value.getTracks().forEach(track => track.stop())//关闭摄像头代码
        videoElement.value.srcObject = null
        cameraActive.value = false
      } else {
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
          navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => {
              videoStream.value = stream
              videoElement.value.srcObject = stream
              cameraActive.value = true
            })
            .catch(error => {
              console.log(error)
              ElMessage.error('获取摄像头失败')
            });
        }
        else {
          ElMessage.error('获取摄像头失败，请检查是否已连接摄像头')
        }

      }
    };

    const handleCheckAllChange = (val) => {//全选按钮
      outboundJadeDataColumn.value = []
      selectedFilters.value = []
      isIndeterminate.value = false;
      if (val) {
        tableFilter.value.forEach(item => {
          item.isSelected = val
          outboundJadeDataColumn.value.push(item)
          selectedFilters.value.push(item.label)
        })
      }

    }

    const handleCheckChange = (val) => {//设置勾选列状态
      let temp = []
      tableFilter.value.forEach(item_t => {
        selectedFilters.value.forEach(item_s => {
          if (item_t.label == item_s) {
            temp.push(item_t)
          }
        })
      })
      if (temp.length < tableFilter.value.length && temp.length > 0) {
        isIndeterminate.value = true
      } else {
        isIndeterminate.value = false
      }
      outboundJadeDataColumn.value = temp
      selectedFilters.value = outboundJadeDataColumn.value.map(item => item.label)
    }

    const handleSelectionChange = (selection) => {
      console.log(selection)
      selection.forEach((item) => {
        tempData.value.push(item.details)
      })
    }

    const ensureJade = () => {//确认出库对象
      try {
        outboundJadeInfoData.value = tempData.value
        console.log(outboundJadeInfoData.value)

        tempData.value = []
        imageUrlList.value = []
        dialogVisibleResult.value = false
      } catch {
        ElMessage.error('请检测完成后再勾选')
      }
    }

    const handleDeleteImg = (imageId) => { //删除出库对象
      ElMessageBox.confirm(
        '是否要删除该对象?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          outboundJadeInfoData.value.forEach(item => {
            if (imageId == item.imageId) {
              outboundJadeInfoData.value.pop(item)
            }
          })
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    }

    const handleCloseResult = () => {
      dialogVisibleResult.value = false
      imageUrlList.value = []
    }

    // 处理图片上传
    const handleUpload = (res) => {
      getJadeCrop({ image_path: res.url.slice(34) }).then((res_crop) => {//切割得到分割后的图列
        if (res_crop.code == 500) {//是否分割出图片
          ElMessage.error(res_crop)
        } else {
          for (var key in res_crop.result) {
            // console.log('key', { imageId: key, imageUrl: res_crop.result[key] });
            imageUrlList.value.push({ imageId: key, imageUrl: res_crop.result[key] })
          }
          let imageIds = imageUrlList.value.map(item => item.imageId)
          console.log('hgasdhfghjasdfiweyuig', imageIds);
          console.log('imageUrlList.value', imageUrlList.value);
          getJadeFeature({ data: imageUrlList.value }).then(res => {
            jadeMatch({ imageIds: imageIds }).then((res_match) => {//匹配翡翠
              if (res_match.match_result == '') {
                ElMessage.error('无法识别该货品')
                imageUrlList.value = []
              } else {
                imageUrlList.value = imageUrlList.value.map(item => {//放入匹配结果
                  const imageId = item.imageId;
                  console.log(item);
                  console.log('res_match', res_match);
                  const bestMatch = Array.isArray(res_match.match_result) ? res_match.match_result[imageId] : '';
                  console.log('匹配的图片' + bestMatch)
                  return { ...item, best_match: bestMatch };
                })
                getJadeInfo({ imageIds: imageUrlList.value.map(i => i.best_match) }).then((jadeInfos) => {//获取翡翠信息
                  jadeInfos.data.forEach(jade => {
                    imageUrlList.value.forEach(img => {
                      if (jade.imageId == img.best_match) {
                        img.matchUrl = jade.imageUrl
                        img.details = jade
                      }
                    })
                  })
                  console.log(imageUrlList.value)
                })
              }
            })
          })
          dialogVisibleResult.value = true  //打开确认列表
        }
      })


    }

    const previewSrcList = (imgUrl) => {//预览图片
      imgPreview.value = []
      imgPreview.value.push('http://8.134.106.197:9001/profile' + imgUrl)
    }

    const changeOutboundType = (value) => {
      // 重置出库列表
      outboundJadeInfoData.value = []
      outboundForm.outboundShow1 = outboundForm.outboundShow2 = outboundForm.outboundShow3 = false
      value == 1 ? outboundForm.outboundShow1 = true : value == 2 ? outboundForm.outboundShow2 = true : outboundForm.outboundShow3 = true
    }

    const getStatus = () => {//得到货品应要改变的状态
      if (outboundForm.outboundShow1) {
        return 1
      } else if (outboundForm.outboundShow2) {
        return 2
      } else {
        return 3
      }

    }

    const onSearch = () => {//确认条码并搜索
      if (outboundForm.jadeCode && outboundForm.jadeCode.trim()) {
        dialogVisibleList.value = true
      } else {
        ElMessage({
          type: 'warning',
          message: '请输入条形码',
        })
        outboundForm.jadeCode = ''
      }
    }

    const onSubmit = () => {
      outboundRef.value.validate().then(() => {
        if (outboundJadeInfoData.value.length == 0) {
          ElMessage.error('请先选择出库货品')
          return
        }
        // 控制借出天数 lendDays
        if(outboundForm.lendDays>60 && outboundForm.lendDays<366){
              ElMessageBox.confirm(
              '请提交主管审批',
              '提示',
              {
                confirmButtonText: 'OK',
                cancelButtonText: 'Cancel',
                type: 'warning',
              }
            )
            
        }
        if(outboundForm.lendDays>365){
            ElMessage.error("最大出借天数为365天");
            return;
        }

        outboundJadeInfoData.value.forEach((item) => {
          altJadeStatus({ id: item.id, status: getStatus() })
        })
        /* 新接口参数修改 */
        const wmsOutboundOrderDO = { ...outboundForm }
        delete wmsOutboundOrderDO.jades
        const wmsJadeList = outboundJadeInfoData.value
        outbound({ ...wmsOutboundOrderDO, wmsJadeList }).then((res) => {
          if (res.code == 200) {
            ElMessage.success('出库成功')
            outboundJadeInfoData.value = []
          } else {
            ElMessage.error(res.msg)
          }

        })
        // 验证通过
      }).catch((error) => {
        //验证失败
        ElMessage.error('请正确填写信息');
      })
    }

    const handleInputNums = (value) => {
  let parsedValue;

  if (value === '') {
    return;
  }

  parsedValue = parseFloat(value);

  if (isNaN(parsedValue)) {
    ElMessage.warning('请输入数字');
    outboundForm.lendDays = '';
    return;
  }

  if (parsedValue < 0 || parsedValue > 365) {
    if (parsedValue > 365) {
      ElMessage.error('提交失败，请重新输入正确出借天数');
    } else {
      ElMessage.warning('请输入 0 到 365 之间的数字');
    }
    outboundForm.lendDays = '';
    return;
  }

  if (parsedValue <= 60) {
    return;
  }

  if (parsedValue > 60 && parsedValue <= 365) {
    // 超过 60 天，提示需要提交审核
    ElMessage.warning('该条记录请提交主管审批');
  }
};

    const radioValue = ref(2)

    // watch(
    //   outboundJadeInfoData,
    //   (newVal, oldVal) => {
    //     outboundJadeInfoData.value = Array.from(new Map(newVal.map(item => [item.id, item])).values());
    //   },
    //   {
    //     deep: true
    //   }
    // )


    watch(radioValue, (newVal, oldVal) => {
      console.log('radioValue', newVal);
      outboundForm.outboundShow1 = outboundForm.outboundShow2 = outboundForm.outboundShow3 = false
      newVal == 1 ? outboundForm.outboundShow1 = true : newVal == 2 ? outboundForm.outboundShow2 = true : outboundForm.outboundShow3 = true
      outboundForm.orderType = newVal
    })

    return {
      outboundJadeInfoData, token, imgPreview, imageUrlList, tempData, clientList,
      outboundForm, tableFilter, outboundJadeDataColumn, selectedFilters, checkAll, isIndeterminate,
      state, outboundOrderRules, outboundRef, match_controll, jadeListData, labelType,
      videoElement, canvasElement, cameraActive, videoStream, radioValue,
      dialogVisibleImg, dialogImageUrl, dialogVisibleDetails, dialogVisibleResult, dialogVisibleList,
      tableData, handleCheckAllChange, handleCheckChange, handleCloseResult, initdialogVisibleList, multipleSelectList,
      handleCurrentChange, changeOutboundType, handlePictureCardPreview, checkPercent,
      handleSizeChange, handleSelectionChange, ensureJade, onSearch, handleDeleteImg, handleSelectListChange,
      triggerCamera, handleUpload, previewSrcList, takePhoto, onSubmit, getStatus, handleConfirm, handleInputNums,
      ...toRefs(state), handleSubmit
    };
  },
});
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
// .front {
//   display: flex;
//   height: 35%;
// }

// .front-left {
//   height: 100%;
//   background-color: #fff;
//   padding: 10px;
//   display: flex;
//   flex-direction: column;
//   align-self: flex-start;
//   gap: 30px;
//   width: 58%;

//   .front-select {
//     width: 80%;
//     margin-left: 50px;
//   }

//   .front-form {
//     .front-input {
//       width: 400px;
//     }


//   }


// }

// .front-right {
//   height: 100%;
//   margin-left: 15px;
//   background-color: #fff;
//   padding: 10px;
//   width: 40%;

//   .right-photo {
//     width: 100%;
//     height: 70%;
//     border: solid 1px;
//   }

//   .rigth-video {
//     flex: auto;
//     width: 100%;
//     height: 100%;
//   }

//   .right-img {
//     flex: auto;
//     width: 100%;
//     height: 100%;
//     position: absolute;
//     top: -9999px;
//     opacity: 0;
//   }

//   .right-action {
//     width: 100%;
//     height: 40px;
//     margin: 10px;
//   }

// }

.front {
  display: flex;
  justify-content: space-between;

  .front-left {
    width: 37%;
    background-color: #fff;
  }

  .front-right {
    width: 62%;
    background-color: #fff;

    .right-photo {
      width: 100%;

      height: 50%;
      border: solid 1px rgb(197, 193, 193);
    }

    .rigth-video {
      flex: auto;
      width: 100%;
      height: 100%;
    }

    .right-img {
      flex: auto;
      width: 100%;
      height: 100%;
      position: absolute;
      top: -9999px;
      opacity: 0;
    }

    .right-action {
      width: 100%;
      height: 40px;
      margin: 10px;
    }
  }
}


.tail {
  background-color: #fff;
  margin-top: 40px;
  padding: 10px;

  .tail-action {
    margin-bottom: 10px;
    display: flex;
  }
}
</style>